import React, { useEffect, useState } from 'react'
import { notification, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { getNewsListApi, delNewsApi, updateNewsApi } from '@/api/news'
const { confirm } = Modal

function usePublish(type) {
  const { username } = JSON.parse(localStorage.getItem('token'))
  const [dataSource, setDataSource] = useState([])

  useEffect(() => {
    getNewsList()
  }, [username, type])

  // 获取列表
  const getNewsList = () => {
    getNewsListApi({
      author: username,
      publishState: type,
      '_expand': 'category'
    }).then(res => {
      setDataSource(res)
    })
  }

  // 发布
  const handlePublish = (item) => {
    updateNewsApi(item.id, {
      ...item,
      publishState: 2,
      publishTime: Date.now()
    }).then(() => {
      getNewsList()
      notification.info({
        message: '通知',
        description: '您可以到【发布管理/已发布】中查看新闻',
        placement: 'bottomRight'
      })
    })
  }

  // 删除
  const handleDelete = (item) => {
    confirm({
      title: '系统提示',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined/>,
      content: '删除后无法恢复,你确定要删除吗?',
      onOk() {
        delNewsApi(item.id).then(() => {
          getNewsList()
          notification.info({
            message: '通知',
            description: '您已删除已下线的新闻',
            placement: 'bottomRight'
          })
        })
      },
      onCancel() {
        console.log('取消删除了')
      }
    })
  }

  // 下线
  const handleSunset = (item) => {
    updateNewsApi(item.id, {
      ...item,
      publishState: 3
    }).then(() => {
      getNewsList()
      notification.info({
        message: '通知',
        description: '您可以到【发布管理/已下线】中查看新闻',
        placement: 'bottomRight'
      })
    })
  }

  return {
    dataSource,
    handlePublish,
    handleDelete,
    handleSunset
  }
}

export default usePublish